package com.demo.tableversion.controller;


import com.demo.tableversion.config.LogAspect;
import com.demo.tableversion.entity.MetaTable;
import com.demo.tableversion.entity.MetaTableVersionHistory;
import com.demo.tableversion.service.IMetaTableService;
import com.demo.tableversion.service.IMetaTableVersionHistoryService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.logging.Level;

@Aspect
@Component
@Slf4j
public class MetaTableUpsertAspect {

    @Autowired
    private IMetaTableService metaTableService;

    @Autowired
    private IMetaTableVersionHistoryService metaTableVersionHistoryService;

    /*@Pointcut("execution(* com.demo.tableversion.service.impl.MetaTableServiceImpl.save*(..))")
    public void log(){}


    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        log.error("doBefore:"+joinPoint.getArgs().toString());

    }*/

    @After(value = "execution(* com.demo.tableversion.service.impl.MetaTableServiceImpl.save*(..))")
    public void doAfter(JoinPoint joinPoint){

        MetaTable metaTable = (MetaTable) joinPoint.getArgs()[0];
        log.error("doAfter:"+metaTable.toString());
        MetaTableVersionHistory metaTableVersionHistory = new MetaTableVersionHistory();
        metaTableVersionHistory.setTableId(metaTable.getId());
        metaTableVersionHistory.setTableName(metaTable.getTablename());
        metaTableVersionHistory.setVersion(metaTable.getVersion());
        metaTableVersionHistoryService.save(metaTableVersionHistory);
    }

    @After(value = "execution(* com.demo.tableversion.service.impl.MetaTableServiceImpl.modify*(..))")
    public void doAfter2(JoinPoint joinPoint){

        MetaTable metaTable = (MetaTable) joinPoint.getArgs()[0];
        log.error("doAfter:"+metaTable.toString());
        MetaTableVersionHistory metaTableVersionHistory = new MetaTableVersionHistory();
        metaTableVersionHistory.setTableId(metaTable.getId());
        metaTableVersionHistory.setTableName(metaTable.getTablename());
        metaTableVersionHistory.setVersion(metaTable.getVersion());
        metaTableVersionHistoryService.save(metaTableVersionHistory);
    }

    /*@AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        log.error("doAfter:"+result.toString());

    }

    @AfterThrowing(throwing = "ex",pointcut = "log()")
    public void AfterThrowing(Exception ex,JoinPoint joinPoint){
        log.error("AfterThrowing:"+ex.getMessage());

    }*/
}
